const jwt = require('jsonwebtoken')
const moment = require('moment');
const { getUserByID,login,adduser,getUserList,updateAavtor ,getUserListCount,
  verifyMobileRepeat,verifyUserNameeRepeat,updateUserByID,delUserByID,getAlluserRoles,
  saveUserRoles,changePWD,saveUserPerms,getUserPerms,getUsersBydeptid} = require('../db/user')
const { result } =require('../config/result')
const {JWT_SECRET} = require('../config/config.dev')
class UserConntroller{
  async getUsersBydeptID(ctx){
    try{
      const {deptid}=ctx.request.body
      //console.log(deptid)
      result.success = true
      result.message = "获取成功"
      result.token=''
      if(deptid){
          const ret= await getUsersBydeptid(deptid)
          result.success = true
          result.message = "获取成功"
          result.token=''
          result.data =ret
      }
      ctx.body = result
    }catch(e){
        result.data = '保存失败' 
        result.message = e.message
        result.success = false
        ctx.body = result
        ctx.app.emit('error',e.message,ctx)  
    } 
  }

  async getUserPerms(ctx)
  {
    try{
      const {userid}=ctx.request.body
     // console.log(userid,menuselect,opselect)
      const ret= await getUserPerms(userid)
      result.success = true
      result.message = "获取成功"
      result.data =ret
      ctx.body = result
    }catch(e){
        result.data = '保存失败' 
        result.message = e.message
        result.success = false
        ctx.body = result
        ctx.app.emit('error',e.message,ctx)  
    } 
  }
  async addUserPerms(ctx)
  {
    try{
      const {userid,menuselect,opselect}=ctx.request.body
     // console.log(userid,menuselect,opselect)
      const ret= await saveUserPerms(userid,menuselect,opselect)
      result.success = true
      result.message = "保存成功"
      result.data =ret
      ctx.body = result
    }catch(e){
        result.data = '保存失败' 
        result.message = e.message
        result.success = false
        ctx.body = result
        ctx.app.emit('error',e.message,ctx)  
    }  
  }

  async addUserRoles(ctx)
  {
    try{
      await saveUserRoles(ctx.request.body)
      result.success = true
      result.message = "保存成功"
      result.data =null
      ctx.body = result
    }catch(e){
        result.data = '保存失败' 
        result.message = e.message
        result.success = false
        ctx.body = result
        ctx.app.emit('error',e.message,ctx)  
    }  
  }

  async getUserRoles(ctx){
    try{
      const {userID} = ctx.request.body
      //console.log('人员ID：',userID)
      const ret =  await getAlluserRoles(userID) 
      result.success = true
      result.message = "获取人员角色列表成功"
      result.data = ret
      ctx.body = result
    }catch(e){
        result.data = null
        result.message = e.message
        result.success = false
        ctx.app.emit('error',e.message,ctx)  
  }  
  }

  async updateUser(ctx){
    try{
      const ret =  await updateUserByID(ctx.request.body) 
      if(ret && ret.length>0){
        result.success = true 
        result.message = "用户更新成功"
        result.data = ret
      }
      else{
        result.success = false
        result.message = '用户更新失败'
        result.data = null
      }  
      ctx.body = result
    }catch(e){
        ctx.app.emit('error',e.message,ctx)  
    } 
  }
  async delUserByID(ctx){
    try{
      const {id} =ctx.request.params
      console.log(ctx.request.params)
      const ret =  await delUserByID(id) 
      if(ret && ret.length>0){
        result.success = true 
        result.message = "用户删除成功"
        result.data = ret
      }
      else{
        result.success = false
        result.message = '用户删除失败'
        result.data = null
      }  
      ctx.body = result
    }catch(e){
        ctx.app.emit('error',e.message,ctx)  
    } 
  }
  async getUserByID(ctx){
    try{
      const {id} =ctx.request.params
      const ret =  await getUserByID(id) 
      if(ret && ret.length>0){
        if(ret[0].timeOfEntry)
          ret[0].timeOfEntry= moment(ret[0].timeOfEntry).format('YYYY-MM-DD')
        result.success = true 
        result.message = "用户获取成功"
        result.data = ret       
      }
      else{
        result.success = false
        result.message = '用户获取失败'
        result.data = null
      }  
      ctx.body = result
    }catch(e){
        ctx.app.emit('error',e.message,ctx)  
    } 
  }
  async verifyusername(ctx){
    try{
      const {id,username} =ctx.request.body
      const ret =  await verifyUserNameeRepeat(id,username) 
      if(ret && ret.length>0){
        result.success = false 
        result.message = "用户名称已经存在"
        result.data = null
        
      }
      else{
        result.success = true
        result.message = '用户名可以使用'
        result.data = null
      }  
      ctx.body = result
    }catch(e){
        ctx.app.emit('error',e.message,ctx)  
    } 
  }
  async verifymobile(ctx){
    try{
      const {id,mobile} =ctx.request.body
      const ret =  await verifyMobileRepeat(id,mobile) 
      if(ret && ret.length>0){
        result.success = false 
        result.message = "手机号已注册"
        result.data = null
        
      }
      else{
        result.success = true
        result.message = '此手机号未注册'
        result.data = null
      }  
      ctx.body = result
    }catch(e){
        ctx.app.emit('error',e.message,ctx)  
    } 
  }
  async adduser(ctx){
    try{
      const ret =  await adduser(ctx.request.body) 
      if(ret && ret.length>0){
        const id=ret[0]
        const siginUser=await getUserByID(id)
        if(siginUser){
          result.success = true 
          result.message = "用户保存成功"
          result.data = siginUser
        }
        else{
          result.success = false 
          result.message = "用户保存失败"
          result.data = null
        }
      }
      else{
        result.success = false
        result.message = '用户保存失败失败'
        result.data = null
      }  
      ctx.body = result
    }catch(e){
        ctx.app.emit('error',e.message,ctx)  
    } 
  }
  uploadavator(ctx){
    // console.log('sssss',ctx.request.files)
    const file = ctx.request.files?.file;
    result.data=null
    if(file)
    {
      result.success=true;
      result.message='上传成功'
      result.data={
        avator:`${ctx.origin}/images/${file.newFilename}`,
        avatorOFileName:file.originalFilename,
        avatorNFileName:file.newFilename,
        savepath:file.filepath
      }
    }   
    else{
      result.success=false;
      result.message='上传失败'

    }
    result.token=''
    result.total=0
    console.log(result  )
    ctx.body=result
  }
  upexcel(ctx){
    //console.log('sssss',ctx.request.files)
    const file = ctx.request.files.file;
    const basename = file.filepath;
    //ctx.body = `${file.filepath}  ${file.originalFilename} ${file.newFilename}`
    ctx.body = { url: `${ctx.origin}/images/${file.newFilename}` };
  }
  downexcel(ctx){
    console.log('down')
  }
  async create(ctx){
    result.success = true
    result.message = "允许访问create"
    result.data = ctx.state.user
    ctx.body = result
  }


  async login(ctx){
    try{
      const {username,password} = ctx.request.body
      const ret =  await login(username,password) 
      if(ret && ret.length>0){
        //生成token返回：id,username,mobile
        const {password,createdtime,updatedtime,isdelete,...tempuser} = ret[0]
        const token = jwt.sign({
          id:tempuser.id,
          username:tempuser.username,
          mobile:tempuser.mobile
          },
          JWT_SECRET,{expiresIn:'1d'}
          )

        //返回用户数据JSON
        result.success = true
        result.message = '登录成功'
        result.token=token
        result.data = tempuser
        ctx.body = result
      }
      else{
        result.data = null
        result.message = '用户名或密码错误'
        result.success = false
        result.token = ''
        ctx.app.emit('error','用户名或密码错误',ctx)  
        return
      }  
    }catch(e){
      result.data = null
        result.message = e.message
        result.success = false
        ctx.app.emit('error',e.message,ctx)  
    }
      
  }
  async changePWD(ctx){
    try{
      const {oldpwd,newpwd,id }= ctx.request.body;
      const ret =  await changePWD(id,oldpwd,newpwd) 
      //console.log(ret)
      switch(ret){
        case -1:
          result.message = '原密码错误'
          break
        case 1:
          result.message = '密码修改成功'
          break
        case -2:
          result.message = '用户不存在'
          break
        default:
          result.message = '密码修改失败'
          break
      }
      result.success = true
      result.data = ret 
      ctx.body = result
    }catch(e){
        ctx.app.emit('error',e.message,ctx)  
    } 
  }
  async getUserList(ctx){
  try{
    const retcount=await getUserListCount(ctx.request.query)
    //console.log(retcount)//[ { total: 25 } ]
    let total = retcount[0].total
    const ret =  await getUserList(ctx.request.query) 
    if(ret && ret.length>0){
      //返回用户数据JSON
      ret.forEach(item=>{
        if(item.timeOfEntry){
          item.timeOfEntry= moment(item.timeOfEntry).format('YYYY-MM-DD')
        }
      })     
      result.total = total
      result.message = '获取用户列表成功'
      result.data = ret
    }
    else{
      result.total = 0
      result.data = null
      result.message = '用户列表为空'
    }  
    result.success = true
    ctx.body = result
  }catch(e){
      result.data = null
      result.message = e.message
      result.success = false
      ctx.app.emit('error',e.message,ctx)  
  }
  }
}

module.exports= new UserConntroller()